<?php

class GroupsController extends Zend_Controller_Action
{
	
	
	public function init() 
	{
		// Add some wonderful stuff arround here someday
	}
	
	public function indexAction()
	{
		/* 
		 * A LEFT JOIN, gives all records that match in the same way
		 * and IN ADDITION an extra record for each unmatched record
		 * in the left table of the join - thus ensuring that every 
		 * group gets a mention.
		 */
		
		/*
		// Get the group list with the parrent name included.
		$groupTable = new Groups();
		$select = $groupTable->select();
		$select->from(array("a" => "groups"))
		       ->joinLeft("groups AS b", "a.parrent_id = b.id", "name AS parrent")
		       ->order( array("parrent_id"));
		       
		$this->view->groups = $groupTable->fetchAll($select);
		*/
		
		$groupTable = new Groups();
		
		$groups = $groupTable->fetchAll();
		foreach($groups as $group) {
			$members[$group->id] = $group->findUsersViaUsersGroups();
		}
		$this->view->groups = $groups;
		$this->view->members = $members;
	}
	
	public function revokeAction() 
	{
		$groupsTable = new Groups();
		$grantsTable = new Grants();
		$rights = Rights::cast(Zend_Registry::getInstance()->get("rights"));
		$f = new Zend_Filter_StripTags();
		
		if ($this->_request->isPost()) {
			$confirm = $this->_request->getParam('confirm');
			$group = $groupsTable->find((int)$this->_request->getParam('group'))->current();
			$handle = $f->filter($this->_request->getParam('handle', null));
			
			if ($confirm=="Yes"  && $rights->getRight($handle)) 
				$grantsTable->delete("group_id = ".$group->id." AND handle = '".$handle."'");
				
			$this->_redirect("/groups/rights/group/".$group->id."/");
		}
		
		$group = $groupsTable->find((int)$this->_request->getParam('group'))->current();
		$handle = $f->filter($this->_request->getParam('handle', null));
		
		$this->view->right = $rights->getRight($handle);
		$this->view->group = $group;
	}
	
	
	public function grantAction()
	{
		$groupsTable = new Groups();
		$grantsTable = new Grants();
		$rights = Rights::cast(Zend_Registry::getInstance()->get("rights"));
		$f = new Zend_Filter_StripTags();
		
		if ($this->_request->isPost()) {
			$confirm = $this->_request->getParam('confirm');
			$group = $groupsTable->find((int)$this->_request->getParam('group'))->current();
			$handle = $f->filter($this->_request->getParam('handle', null));
			
			if ($confirm=="Yes" && $rights->getRight($handle)) 
				$grantsTable->createRow(array("group_id" => $group->id, "handle" => $handle))->save();
				
			$this->_redirect("/groups/rights/group/".$group->id."/");
		}
		
		$group = $groupsTable->find((int)$this->_request->getParam('group'))->current();
		$handle = $f->filter($this->_request->getParam('handle', null));
		
		$this->view->right = $rights->getRight($handle);
		$this->view->group = $group;
	}
	
	public function rightsAction()
	{
		$groupsTable = new Groups();
		$grantsTable = new Grants();
		$rights = Rights::cast(Zend_Registry::getInstance()->get("rights"));
		
		// Fetch the group and associated rights
		$group = $groupsTable->find((int)$this->_request->getParam('group'))->current();
		if ($group) $grants = $group->findGrants();
		
		// Build a grant list we can use for easy right checking in the view
		$grantList[] = array();
		if (@count($grants)) foreach($grants as $grant) $grantList[$grant->handle] = true;
		
		$this->view->group = $group;
		$this->view->grants = $grantList;
		$this->view->rights = $rights;
	}
	
	public function removememberAction()
	{
		$usersGroupsTable = new UsersGroups();
		
		// Have a form been sumbitted?
		if ($this->_request->isPost()) {	
			$confirm = $this->_request->getParam('del');
			$groupId = (int)$this->_request->getParam('group_id');
			$userId = (int)$this->_request->getParam('user_id');
			
			if ($confirm=="Yes") $usersGroupsTable->delete("user_id = ".$userId." AND group_id =".$groupId);
			$this->_redirect("/groups/members/group/".$groupId."/");
		}
		
		$groupId = (int)$this->_request->getParam('group');
		$userId = (int)$this->_request->getParam('user');
		
		$userGroup = $usersGroupsTable->fetchRow("user_id=".$userId." AND group_id=".$groupId);
		
		if($userGroup) {
			$this->view->group = $userGroup->findParentRow("Groups");
			$this->view->user = $userGroup->findParentRow("Users");
		}
	}
	
	public function membersAction() 
	{
		$groupsTable = new Groups();
		$usersTable = new Users();
		
		$id = (int)$this->_request->getParam('group');
		if ($id > 0) {	
			$group = $groupsTable->fetchRow("id=".$id);
		}

		if ($group == null) return;
		
		// Have a form been sumbitted?
		if ($this->_request->isPost()) {
			
			$sumbit = $this->_request->getParam("submit");
			$id = (int)$this->_request->getParam("user","-1");

			if ($sumbit == "Add" && $usersTable->fetchRow("id = ".$id)) {	
				$usersGroupsTable = new UsersGroups();
				$usersGroupsTable->createRow(array("user_id" => $id, "group_id" => $group->id))->save();
			}
		}
		
		$members = $group->findUsersViaUsersGroups();

		// Construct a comma seperated list of the ids of members in this group
		foreach($members as $member)  $memberIds[] = $member->id;
		if(@is_array($memberIds)) $memberIds = implode($memberIds, ",");
		else $memberIds = "-1";
	
		// Get a list of members not in the group	
		$select = $usersTable->select();
		$select->where("id NOT IN (".$memberIds.")");
		// Format the list so it can used for a html select box
		foreach($usersTable->fetchAll($select) as $user) 
			$excluded[$user->id] = $user->nickname;
			
		// Construct a form
		$form = new Zend_Form();
		
		$userSelect = new Zend_Form_Element_Select("user");
		$userSelect->addMultiOption("0", "...");
		if (@is_array($excluded)) $userSelect->addMultiOptions($excluded);
		
		$userSubmit = new Zend_Form_Element_Submit("submit");
		$userSubmit->setLabel("Add");
		           
		$form->addElements(array($userSelect, $userSubmit));

		$this->view->group = $group;
		$this->view->members = $members;
		$this->view->form = $form;
	}
	
	public function createAction()
	{	
		// Construct a simple form for the group name
		$form = new Zend_Form();
		
		$nameElement = new Zend_Form_Element_Text('name');
		$nameElement->setLabel('Group name')
		            ->setRequired(true)
                    ->addValidator('NotEmpty')
                    ->addPrefixPath('Form_Validator', 'forms/validators/', 'validate')
                    ->addValidator('UniqueDBTableEntryValidator',false,array('table'=>new Groups(), 'field'=>'name'));
                    
        $defaultElement = new Zend_Form_Element_Checkbox('default');      
        $defaultElement->setLabel('Default group?');   
                    
        $submit = new Zend_Form_Element_Submit('submit');
        $submit->setLabel('Create');
        
        $form->addElements(array($nameElement, $defaultElement, $submit));
        
        if ($this->_request->isPost()) {
            $formData = $this->_request->getPost();
            if ($form->isValid($formData)) {
                
                $default = 0;
                if (!empty($formData['default'])) {
                    $default = 1;
                }
                $groupsTable = new Groups();
                
                $groupId = $groupsTable->insert(array('name' => $formData['name'], 
                                                      'def'  => $default));
                return $this->_helper->redirector('index');

            } else {
                $form->populate($formData);
            }
        } 
                    
        $this->view->form = $form;
	}
	
	public function deleteAction()
	{
	    $group = Groups::getById($this->_request->getParam('group'));
        
	    if (!$group) {
	        return; 
	    }
	    
	    if ($this->_request->isPost()) {
	        $group->delete();
	        return $this->_helper->redirector('index');
	    }
	    
	    $this->view->group = $group;
	}
	
	public function showRightsAction()
	{
		$rights = Rights::cast(Zend_Registry::getInstance()->get("rights"));
		$this->view->rights = $rights;
	}
	
}